from datetime import date 
from google.appengine.api import urlfetch
import re
from Parser import HorizontalParser,VerticalParser
from Formats import *
from Debug import *


class FRCEvent:
	def __init__(self,EventCode,Year=None):
		if Year == None:
			Year = date.today().year
		self.Year = int(Year)
		self.EventCode = EventCode
		self.QualificationResults = None
		self.EliminationResults = None
		self.Awards = None
		self.Rankings = None
		self.QualificationSchedule = None
		self.EliminationSchedule = None
		self.TeamList = None
	
	def LoadURL(self,URL):
		Content = urlfetch.fetch(URL).content
		#Admittedly, this is a hack. Pat uses window.location= to redirect instead of a proper HTTP response so this is the easiest way
		URL = re.search("window.location.*?=.*?\"(.*)\"",Content).group(1)
		try:
			DebugPrint("URL="+URL)
			return urlfetch.fetch(URL).content
		except:
			return ""
	
	def GetCacheTime(self):
		CacheTime = 600 #10 minutes
		if self.QualificationResults != None or self.EliminationResults != None:
			CacheTime = 60
		return CacheTime
	
	def GetQualificationResults(self):
		if self.QualificationResults == None:
			URL = "http://frclinks.com/e/m/%s/%i"%(self.EventCode,self.Year)
			Content = self.LoadURL(URL)
			QualificationResultsHorizontalParser = HorizontalParser(Content)
			self.QualificationResults = QualificationResultsHorizontalParser.GetTableData(TableIndex=2,HasHeaders=True,HasTitle=True)
		return self.QualificationResults
	
	def GetEliminationResults(self):
		if self.EliminationResults == None:
			URL = "http://frclinks.com/e/m/%s/%i"%(self.EventCode,self.Year)
			Content = self.LoadURL(URL)
			EliminationResultsHorizontalParser = HorizontalParser(Content)
			self.EliminationResults = EliminationResultsHorizontalParser.GetTableData(TableIndex=3,HasHeaders=True,HasTitle=True)
		return self.EliminationResults
	
	def GetAwards(self):
		if self.Awards == None:
			URL = "http://frclinks.com/e/a/%s/%i"%(self.EventCode,self.Year)
			Content = self.LoadURL(URL)
			AwardsHorizontalParser = HorizontalParser(Content)
			self.Awards = AwardsHorizontalParser.GetTableData(TableIndex=2,HasTitle=False,HasHeaders=True)
		return self.Awards
	
	def GetRankings(self):
		if self.Rankings == None:
			URL = "http://frclinks.com/e/r/%s/%i"%(self.EventCode,self.Year)
			Content = self.LoadURL(URL)
			RankingsParser = HorizontalParser(Content)
			self.Rankings = RankingsParser.GetTableData(TableIndex=2,HasTitle=False,HasHeaders=True)
		return self.Rankings
	
	def GetQualificationSchedule(self):
		if self.QualificationSchedule == None:
			URL = "http://frclinks.com/e/s/%s/%i"%(self.EventCode,self.Year)
			Content = self.LoadURL(URL)
			QualificationScheduleParser = HorizontalParser(Content)
			self.QualificationSchedule = QualificationScheduleParser.GetTableData(TableIndex=2,HasTitle=True,HasHeaders=True)
		return self.QualificationSchedule		
	
	def GetEliminationSchedule(self):
		if self.EliminationSchedule == None:
			URL = "http://www2.usfirst.org/%icomp/events/%s/scheduleelim.html"%(self.Year,self.EventCode)
			Content = urlfetch.fetch(URL).content
			EliminationScheduleParser = HorizontalParser(Content)
			self.EliminationSchedule = EliminationScheduleParser.GetTableData(TableIndex=2,HasTitle=True,HasHeaders=True)
		return self.EliminationSchedule
	
	def GetTeamList(self):
		if self.TeamList == None:
			DebugPrint(self.EventCode)
			URL = "http://frclinks.com/e/%s/%i"%(self.EventCode,self.Year)
			Content = self.LoadURL(URL).decode('utf-8')
			TeamListParser = HorizontalParser(Content)
			self.TeamList = TeamListParser.GetTableData(TableIndex = 0,HasTitle = False, HasHeaders = False,SkipRows=4, NewHeaders=["Location","Team_Name","Team_Number"])
		return self.TeamList
	


def GetTeamInfo(TeamNo,HistoryFormat=None):
	URL = "http://frclinks.com/t/%s"%(TeamNo)
	Content = urlfetch.fetch(URL).content
	#Admittedly, this is a hack. Pat uses window.location= to redirect instead of a proper HTTP response so this is the easiest way
	URL = re.search("window.location.*?=.*?\"(.*)\"",Content).group(1)
	Content = urlfetch.fetch(URL).content
	TeamParser = VerticalParser(Content)
	if HistoryFormat == None:
		Data = TeamParser.GetTableData(TableIndex=1,HasTitle=True,HasHeaders=False,SkipRows = 2,ProcessRows=7,NewHeaders = ["Team_Number","Team_Name","Team_Location","Rookie_Season","Team_Nickname","Team_Motto","Team_Website"])[0]
		Data["History"]=GenerateJSON(HorizontalParser(Content).GetTableData(TableIndex=4,HasTitle=False,HasHeaders=True,NewHeaders=["Year","Event","Awards"]))
		return Data
	else:
		Data = TeamParser.GetTableData(TableIndex=1,HasTitle=True,HasHeaders=False,SkipRows = 2,ProcessRows=7,NewHeaders = ["Team_Number","Team_Name","Team_Location","Rookie_Season","Team_Nickname","Team_Motto","Team_Website"])[0]
		Data["History"]=HistoryFormat.Generate(Body=HorizontalParser(Content).GetTableData(TableIndex=4,HasTitle=False,HasHeaders=True,NewHeaders=["Year","Event","Awards"]))
		return Data

def GetTeamHistory(TeamNo):
	URL = "http://frclinks.com/t/%s"%(TeamNo)
	Content = urlfetch.fetch(URL).content
	#Admittedly, this is a hack. Pat uses window.location= to redirect instead of a proper HTTP response so this is the easiest way
	URL = re.search("window.location.*?=.*?\"(.*)\"",Content).group(1)
	Content = urlfetch.fetch(URL).content
	return HorizontalParser(Content).GetTableData(TableIndex=4,HasTitle=False,HasHeaders=True,NewHeaders=["Year","Event","Awards"])
	

